package sk.tuke.constraintbuilder.views.components;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerDropAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.TransferData;

import sk.tuke.constraintbuilder.editor.RulesetEditorController;
import sk.tuke.constraintbuilder.model.Constraint;

public class RulesetEditorDNDListener extends ViewerDropAdapter implements DragSourceListener {
	
	private ListViewer viewer;
	private RulesetEditorController controller;

	public RulesetEditorDNDListener(Viewer viewer, RulesetEditorController controller) {
		super(viewer);
		this.viewer = (ListViewer) viewer;
		this.controller = controller;
	}

	@Override
	public void dragSetData(DragSourceEvent event) {
		IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
		Object element = selection.getFirstElement();
		if(element instanceof Constraint){
			Constraint constraint = (Constraint) element;
			if (TextTransfer.getInstance().isSupportedType(event.dataType)) {
				event.data = String.valueOf(constraint.getId());
			}
		}else{
			System.out.println("Data does not have correct format for type");
		}
		
	}
	
	@Override
	public boolean performDrop(Object data) {
		int id = -1;
		try{
			id = Integer.parseInt((String) data);
		}catch(Exception e){
			return false;
		}
		if(id!=-1){
			controller.addConstraintToRuleset(id);
			viewer.refresh();
			return true;
		}
		return false;
	}

	@Override
	public boolean validateDrop(Object target, int operation, TransferData transferType) {
		return true;	
	}
	
	@Override
	public void dragStart(DragSourceEvent event) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void dragFinished(DragSourceEvent event) {
		// TODO Auto-generated method stub
		
	}


}
